#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File:modify_time.py
@Author:Josco
@Date:2022/09/28 11:01:58
@Version:1.0
@Description: 修改文件时间的类
'''

from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time  # 可以忽视这个 Time 报错（运行程序还是没问题的）
import time


class modify_file_time(object):
    def __init__(self) -> None:
        pass

    def modify_file_time(self, file_path, create_time, modify_time, access_time, offset=(0, 1, 2)):
        """
        用来修改任意文件的相关时间属性，时间格式：YYYY-MM-DD HH:MM:SS 例如：2019-02-02 00:01:02
        :param file_path: 文件路径名
        :param create_time: 创建时间
        :param modify_time: 修改时间
        :param access_time: 访问时间
        :param offset: 时间偏移的秒数,tuple格式，顺序和参数时间对应
        """
        try:
            format = "%Y-%m-%d %H:%M:%S"  # 时间格式
            c_time = self.time_offset_and_struct(
                create_time, format, offset[0])
            m_time = self.time_offset_and_struct(
                modify_time, format, offset[1])
            a_time = self.time_offset_and_struct(
                access_time, format, offset[2])
            fh = CreateFile(file_path, GENERIC_READ |
                            GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, 0)
            create_times = Time(time.mktime(c_time))
            access_times = Time(time.mktime(a_time))
            modify_times = Time(time.mktime(m_time))
            SetFileTime(fh, create_times, access_times, modify_times)
            CloseHandle(fh)
            return 0
        except:
            return 1

    def time_offset_and_struct(self, times, format, offset):
        return time.localtime(time.mktime(time.strptime(times, format)) + offset)
